package com.offcn.project.controller;

import com.alibaba.fastjson.JSON;
import com.offcn.dycommon.enums.ProjectStatusEnume;
import com.offcn.dycommon.response.AppResponse;
import com.offcn.project.contants.ProjectConstant;
import com.offcn.project.po.TReturn;
import com.offcn.project.service.ProjectCreateService;
import com.offcn.project.vo.req.ProjectBaseInfoVo;
import com.offcn.project.vo.req.ProjectRedisStorageVo;
import com.offcn.project.vo.req.ProjectReturnVo;
import com.offcn.vo.BaseVo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;

import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;

@Api(tags = "项目基本功能模块（创建、保存、项目信息获取、文件上传等）")
@RestController
@RequestMapping("project")
@Slf4j
public class ProjectCreateController {

    @Autowired
    private ProjectCreateService projectCreateService;

    @Autowired
    private StringRedisTemplate redisTemplate;

    @ApiOperation("项目发起第1步-阅读同意协议")
    @GetMapping("init")
    public AppResponse<String> init(BaseVo vo){
      //获取请求的token
        String accessToken = vo.getAccessToken();

        //根据accessToken去redis获取对应用户编号
        String memberId = redisTemplate.opsForValue().get(accessToken);

        //判断用户编号是否为空
        if(StringUtils.isEmpty(memberId)){
            //禁止继续创建项目
            return AppResponse.fail("用户登录验证失败");
        }

        //转换用户编号为Integer
        int id = Integer.parseInt(memberId);
        //调用项目创建第一步方法 初始化项目
        String projectToken = projectCreateService.initProjectCreate(id);

        return AppResponse.ok(projectToken);

    }

    @ApiOperation("项目第二步：保存项目信息")
    @PostMapping("savebaseInfo")
    public AppResponse<String> savebaseInfo(ProjectBaseInfoVo vo){
        //1、根据项目token，从redis缓存读取项目存储在redis的信息
        String jsonStr = redisTemplate.opsForValue().get(ProjectConstant.TEMP_PROJECT_PREFIX + vo.getProjectToken());

        log.info("jsonStr:"+jsonStr);
        //2、还原json字符串为 项目redis存储对象
        ProjectRedisStorageVo projectRedisStorageVo = JSON.parseObject(jsonStr, ProjectRedisStorageVo.class);

        log.info("vo用户提交数据:{}",vo);
        //3、把用户表单收集到的项目基本信息属性，复制到redis项目对象
        BeanUtils.copyProperties(vo,projectRedisStorageVo);

        log.info("RedisVo:{}",projectRedisStorageVo);
        //4、把最新的redis项目对象转换成字符串
        String jsonString = JSON.toJSONString(projectRedisStorageVo);
        //5、把json字符串写入到redis
        redisTemplate.opsForValue().set(ProjectConstant.TEMP_PROJECT_PREFIX+vo.getProjectToken(),jsonString);

        return AppResponse.ok("OK");
    }

    @ApiOperation("项目第三步：项目回报")
    @PostMapping("saveReturnInfo")
    public AppResponse<Object> saveReturnInfo(@RequestBody List<ProjectReturnVo> pro){
        log.info("-------pro---:{}",pro);
        //从项目回报集合获取第一个回报对象
        ProjectReturnVo projectReturnVo = pro.get(0);
        //从项目回报对象获取项目token
        String projectToken = projectReturnVo.getProjectToken();
        //根据项目token，读取redis中存储的项目信息
        String jsonStr = redisTemplate.opsForValue().get(ProjectConstant.TEMP_PROJECT_PREFIX + projectToken);

        //把读取到json字符串转换为项目redis存储对象
        ProjectRedisStorageVo projectRedisStorageVo = JSON.parseObject(jsonStr, ProjectRedisStorageVo.class);

        //创建集合存储项目回报的PO
        List<TReturn> returns=new ArrayList<>();
        //遍历项目回报的vo
        for (ProjectReturnVo returnVo : pro) {
            TReturn tReturn = new TReturn();
            //复制vo属性值到po
            BeanUtils.copyProperties(returnVo,tReturn);
            //把回报po存储到po集合
            returns.add(tReturn);
        }

        log.info("-------pro:{}"+returns);
        //把项目回报集合关联到项目redis存储对象
        projectRedisStorageVo.setProjectReturns(returns);

        //把项目redis存储对象转换为json字符串
        String jsonString = JSON.toJSONString(projectRedisStorageVo);
        //存储到redis
        redisTemplate.opsForValue().set(ProjectConstant.TEMP_PROJECT_PREFIX+projectToken,jsonString);

        return AppResponse.ok("OK");

    }

    @ApiOperation("项目发起第4步-项目保存项目回报信息")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "accessToken",value = "用户令牌",required = true),
            @ApiImplicitParam(name = "projectToken",value="项目标识",required = true),
            @ApiImplicitParam(name="ops",value="用户操作类型 0-保存草稿 1-提交审核",required = true)})
    @PostMapping("/submit")
    public AppResponse<Object> submit(String accessToken,String projectToken,String ops){

        //1、使用accessToken从redis读取用户编号
        String memberId = redisTemplate.opsForValue().get(accessToken);
        if(StringUtils.isEmpty(memberId)){
            return AppResponse.fail("用户无权限，请登录");
        }

        //2、根据项目token从redis读取数据
        String jsonStr = redisTemplate.opsForValue().get(ProjectConstant.TEMP_PROJECT_PREFIX + projectToken);

        ProjectRedisStorageVo projectRedisStorageVo = JSON.parseObject(jsonStr, ProjectRedisStorageVo.class);

        //3、判断用户操作类型是否为空
        if(!StringUtils.isEmpty(ops)){


            if(ops.equals("1")) {
                //4、如果操作类型是 1、提交保存
                ProjectStatusEnume auth = ProjectStatusEnume.SUBMIT_AUTH;

                //5、调用项目保存服务，保存项目到数据库
                projectCreateService.saveProjectInfo(auth, projectRedisStorageVo);

                return AppResponse.ok(null);
            }else  if(ops.equals("0")){
                //6、临时存储
                ProjectStatusEnume auth = ProjectStatusEnume.DRAFT;
                //7、保存到数据库
                projectCreateService.saveProjectInfo(auth,projectRedisStorageVo);

                return AppResponse.ok(null);
            }
        }else {
            AppResponse<Object> appResponse = AppResponse.fail(null);
            appResponse.setMsg("不支持此操作");
            return appResponse;
        }

        return AppResponse.fail(null);
    }
}
